#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>

#define PIPE_SIZE 1024

int main(){
  int pipefd[2];
  char buffer[PIPE_SIZE] = {0};
  if(pipe(pipefd) < 0){
    perror("make pipe");
    return 0;
  }
  int pid = fork();
  if(pid < 0){
    perror("fork");
    exit(-1);
  }
  else if(pid == 0){
    //关闭写端
    close(pipefd[1]);
    int len;
    while(1) {
      memset(buffer, 0, PIPE_SIZE);
      len = read(pipefd[0], buffer, PIPE_SIZE);
      if(len == -1){
        perror("read");
        sleep(2); 
      }
      printf("我读到数据了!:%s", buffer);
    }
    //sleep(3);
  }
  else{
    //关闭读端
    close(pipefd[0]);
    int len;
    while(fgets(buffer, PIPE_SIZE, stdin)){
      len = strlen(buffer);
      if(write(pipefd[1], buffer, len) != len){
        perror("write");
        sleep(2);
      }
      else{
        printf("成功写入%d个字符\n", len);
      }
      memset(buffer, 0, PIPE_SIZE);
    }
  }
  return 0;
}
